<script lang="ts">
	import type { RoadmapInfo } from '$lib/api/proto/roadmap_api';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import EditorJS from '@editorjs/editorjs';

	interface Props {
		roadmapInfo?: RoadmapInfo;
		onCancel: () => void;
		onOk: () => void;
	}

	const props: Props = $props();

	let roadmapName = $state(props.roadmapInfo?.basicInfo?.name ?? '');

	let editor: EditorJS | null = $state(null);

	async function createRoadmap() {
		if (editor == null || userStore.userSession == null) {
			return;
		}
		let descData = await editor.save();
		await callApi(
			appStore.roadmapApiClient.create({
				sessionId: userStore.userSession,
				basicInfo: {
					name: roadmapName.trim(),
					desc: JSON.stringify(descData),
					enableJoinApply: false
				}
			}).response
		);
		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '创建成长路线图成功',
			keepTime: 2000
		});
	}

	async function updateRoadmap() {
		if (props.roadmapInfo == undefined || editor == null || userStore.userSession == null) {
			return;
		}
		let descData = await editor.save();
		await callApi(
			appStore.roadmapApiClient.update({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapInfo.roadmapId,
				basicInfo: {
					name: roadmapName.trim(),
					desc: JSON.stringify(descData),
					enableJoinApply: false
				}
			}).response
		);
		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '修改成长路线图成功',
			keepTime: 2000
		});
	}
</script>

<dialog class="modal modal-open">
	<div class="modal-box flex-col space-y-4 w-[800px] max-w-none">
		<h3 class="text-lg font-bold">
			{props.roadmapInfo == undefined ? '创建路线图' : '修改路线图'}
		</h3>
		<label class="label w-full">
			<span class="label w-[60px] text-right inline-block pr-[10px]">名称:</span>
			<input type="text" class="input w-full" bind:value={roadmapName} />
		</label>
		<h4 class="text-base font-bold">简介</h4>
		<SimpleEditor
			sizeClass="min-h-[300px] border-2 border-base-200 max-h-[300px]"
			data={props.roadmapInfo?.basicInfo?.desc}
			placeholder="请输入路线图简介"
			onInit={(tmpEditor) => (editor = tmpEditor)}
		/>
		<div class="modal-action">
			<button class="btn" onclick={() => props.onCancel()}>取消</button>
			<button
				class="btn btn-primary"
				disabled={roadmapName.trim() == '' || editor == null}
				onclick={() => {
					if (props.roadmapInfo == undefined) {
						createRoadmap();
					} else {
						updateRoadmap();
					}
				}}>{props.roadmapInfo == undefined ? '创建' : '修改'}</button
			>
		</div>
	</div>
	<div class="modal-backdrop">
		<button onclick={() => props.onCancel()}>close</button>
	</div>
</dialog>
